import { Component, OnInit } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SellDeliveryActivitiesService } from './sell-delivery-activities.service';
import { DatePipe } from '@angular/common';
import { PermissionService } from 'src/app/service/permission.service';

@Component({
  selector: 'app-sell-delivery-activities',
  templateUrl: './sell-delivery-activities.component.html',
  styleUrls: ['./sell-delivery-activities.component.scss'],
  providers: [DatePipe]
})
export class DeliveryActivitiesComponent implements OnInit {

  // seach
  seachParams: any = {
    userId: '',
    userName: '',
    platform: '',
    createTime: '',
    endTime: '',
  };
  channlSelected: any = [];
  dateArrs: any = [];

  // 渠道下拉
  channlOptions: any = [];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // Modal
  isExamineVisible: boolean = false;
  adoptLoading: boolean = false;
  adoptNotLoading: boolean = false;
  auditDesc: string = '';
  operationItem: any = {};

  constructor(
    public permission: PermissionService,
    private modal: NzModalService,
    private message: NzMessageService,
    private datePipe: DatePipe,
    private services: SellDeliveryActivitiesService
  ) { }

  ngOnInit(): void {
    this.getDictChannelData();
    this.loadTable();
  }

  // 查询渠道list
  async getDictChannelData() {
    try {
      const res: any = await this.services.getDictList('channel');
      if (res.code == 0) {
        this.channlOptions = res.data.list || [];
      } else {
        this.message.error(res.message || '渠道列表获取失败');
      }
    } catch (error: any) {
      this.channlOptions = [];
      this.message.error(error);
    }
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getActivityList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const { records, total } = res.data || {};
        this.tableData = records || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message || '表格数据获取失败');
      }
    } catch (error: any) {
      this.tableParams.tableLoading = false;
      this.tableData = [];
      this.tableParams.total = 0;
    }
  }

  // Time Change
  timeChange(result: any) {
    this.seachParams.createTime = result.length ? this.datePipe.transform(new Date(result[0]), 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(new Date(result[1]), 'yyyy-MM-dd') : '';
  }

  // Channl Change
  channlChange(event: any) {
    this.seachParams.platform = event.join(',');
  } 

  // 查询
  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  // 重置
  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = ''
    }
    this.channlSelected = [];
    this.dateArrs = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  // Export Table
  async exportInterface() {
    try {
      const res: any = await this.services.exportActivity();
      if (res.code != 0) {
        this.message.error(res.message || '导出失败');
      }
    } catch (error: any) {
      if (error.url) {
        this.downLoad(error.url);
      }
    }
  }
  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '<b>确认导出？</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.exportInterface();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  // open modal
  openModal(item: any) {
    this.operationItem = item;
    this.auditDesc = '';
    this.isExamineVisible = true;
  }
  handleCancel() {
    this.isExamineVisible = false;
  }

  /**
   * 审核
   * @param state 1：通过，2：不通过
   */
  async subExamine(state: Number) {
    // 不通过：**备注必填**
    if (state == 2 && !this.auditDesc) {
      this.message.warning('请先填写备注');
      return
    }

    let params = {
      id: this.operationItem.id,
      status: state,
      auditReason: this.auditDesc
    }
    state == 1 ? this.adoptLoading = true : this.adoptNotLoading = true;
    const res: any = await this.services.activityExamine(params);
    this.loadingHide();
    
    if (res.code == 0) {
      this.message.success('操作成功');
      this.isExamineVisible = false;
      this.loadTable();
    } else {
      this.message.error(res.message || '操作失败');
    }
  }
  loadingHide() {
    this.adoptLoading = false;
    this.adoptNotLoading = false;
  }

  // 渠道文字
  textConversion(state: number) {
    if (state && this.channlOptions.length) {
      let tempObj = this.channlOptions.find((item: any) => {
        return item.content == state;
      })
      return tempObj.name || '-';
    } else {
      return '-';
    }
  }

  // downLoad
  downLoad(url: string) {
    const link = document.createElement('a');
    link.href = url;
    link.click();
    setTimeout(() => {
      link.remove();
    }, 2500);
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
